<?php
class mdl_field extends ujn_model {

	protected function __construct() {	
		parent::__construct();
		$this->db_name		= '__' . GAME . '_common';
		$this->tbl_name		= __CLASS__;
		$this->_db			= $this->mysql('adam');
	}

	function makeUserInfo($uid, $name, $nick, $icon, $sex, $flds = array()) {
		$name = $this->escape($name);
		$nick = $this->escape($nick);

		!isset($flds['fld1']) && $flds['fld1'] = '';
		!isset($flds['fld2']) && $flds['fld2'] = '';
		!isset($flds['fld3']) && $flds['fld3'] = '';
		!isset($flds['fld4']) && $flds['fld4'] = '';
		!isset($flds['fld5']) && $flds['fld5'] = '';

		$_sql =<<<EOT
insert into {$this->tbl_name} set
	`uid` = '$uid', `name` = '$name', `nick` = '$nick', `icon` = '$icon', `sex` = '$sex', `status` = '0',
	`fld1` = '{$flds['fld1']}', `fld2` = '{$flds['fld2']}', `fld3` = '{$flds['fld3']}', `fld4` = '{$flds['fld4']}', `fld5` = '{$flds['fld5']}' ;
EOT;
		$this->_db->query($_sql);
	}

	function updateUserInfo($uid, $name, $nick, $icon, $sex, $flds = array()) {
		$name = $this->escape($name);
		$nick = $this->escape($nick);

		!isset($flds['fld1']) && $flds['fld1'] = '';
		!isset($flds['fld2']) && $flds['fld2'] = '';
		!isset($flds['fld3']) && $flds['fld3'] = '';
		!isset($flds['fld4']) && $flds['fld4'] = '';
		!isset($flds['fld5']) && $flds['fld5'] = '';

		$_sql =<<<EOT
update {$this->tbl_name} set
	`uid` = '$uid', `name` = '$name', `nick` = '$nick', `icon` = '$icon', `sex` = '$sex', `status` = '0',
	`fld1` = '{$flds['fld1']}', `fld2` = '{$flds['fld2']}', `fld3` = '{$flds['fld3']}', `fld4` = '{$flds['fld4']}', `fld5` = '{$flds['fld5']}'
where `uid`='$uid';
EOT;
		$this->_db->query($_sql);
		$this->removeCache($uid);
	}

	function removeCache($uid) {
		$this->mc()->delete(mdl_ckey::getck(mdl_ckey::user_by_uid, $uid));
	}

	function getUserInfoByUID($uid) {

		$uck = mdl_ckey::getck(mdl_ckey::user_by_uid, $uid);

		$_omc = $this->mc();
		$udata	= $_omc->get($uck);
		if(false == $udata || empty($udata)) {
			// query database;
			$_sql = "select * from {$this->tbl_name} where `uid` = '$uid';";
			$udata = $this->_db->getOne($_sql, MYSQL_ASSOC);
			if(false != $udata) $_omc->set($uck, json_encode($udata), 0);
		} else {
			$udata = json_decode($udata, true);
		}
		return $udata;
	}
	function getAllUser($limit = 100) { // just for alpha

		$_sql = "select * from {$this->tbl_name} limit $limit;";
		$data = $this->_db->getAll($_sql, MYSQL_ASSOC);		
		return $data;
	}

    /**
     * 单例模型
     * @return mdl_field
     */
	static function getInstance() {
        return parent::getInstance(__CLASS__);
	}
}